package com.badou.project.rest.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.RegEx;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.io.findfile.RegExpFindFile;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.badou.project.rest.ReturnCodeEnum;
import com.badou.project.rest.service.IBaseRestService;
import com.badou.project.rest.vo.ApiReturnVO;
import com.badou.security.ssl.token.pojo.Token;
import com.badou.security.ssl.token.service.ITokenService;
import com.badou.tools.common.util.ParamUtils;

public class AuthorityInterceptor  extends HandlerInterceptorAdapter {  

	//日志
	protected Logger logger = Logger.getLogger(AuthorityInterceptor.class);
	/**
	 * 返回对象
	 */
	protected ApiReturnVO returnVO;
	@Autowired
	private IBaseRestService baseRestService;
	@Autowired
	private ITokenService tokenService;
	
	 /**
     * preHandle方法是进行处理器拦截用的，顾名思义，该方法将在Controller处理之前进行调用，
     * SpringMVC中的Interceptor拦截器是链式的，可以同时存在多个Interceptor，
     * 然后SpringMVC会根据声明的前后顺序一个接一个的执行，
     * 而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。
     * SpringMVC的这种Interceptor链式结构也是可以进行中断的，
     * 这种中断方式是令preHandle的返回值为false，当preHandle的返回值为false的时候整个请求就结束了。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	returnVO = new ApiReturnVO();
    	response.setCharacterEncoding("UTF-8");  
		response.setHeader("Content-Type", "text/html;charset=UTF-8");//这句话是解决乱码的  
    	String token = ParamUtils.getParameter(request, "access_token");
        Token tokenEntity = tokenService.getTokenEntityByToken(token);
      	String methodName = request.getRequestURI();
      	methodName = StringUtils.remove(methodName,request.getContextPath());
      	Map<String,Object> result = baseRestService.authPermission(tokenEntity, methodName);
    	boolean isSuccess = (boolean) result.get("isSuccess");
    	String message =  (String) result.get("message");
    	if(!isSuccess)
    	{
    		returnVO.setReturnMsg(ReturnCodeEnum.FAIL.getReturnMsg()+message);
			returnVO.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
			response.getWriter().write(JSONObject.fromObject(returnVO).toString());  
    		return false;
    	}
    	request.setAttribute("logId", result.get("logId"));
    	return true;
    }
	public ApiReturnVO getReturnVO() {
		return returnVO;
	}
	public void setReturnVO(ApiReturnVO returnVO) {
		this.returnVO = returnVO;
	}


	/**
	 * 切割ip地址
	 * @param ipaddress
	 * @return
	 */
	private List<String> getIpsFromStr(String ipaddress) {
		if(ipaddress==null){
			return null;
		}
		String[] strs = ipaddress.split("，");
		List<String> ips = new ArrayList<String>();
		for(int i=0; i<strs.length; i++){
			ips.add(strs[i].trim());
		}
		return ips;
	}  
	 public static String getIpAddress(HttpServletRequest request) {  
	        String ip = request.getHeader("x-forwarded-for");  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("Proxy-Client-IP");  
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("WL-Proxy-Client-IP");  
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("HTTP_CLIENT_IP");  
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
	        }  
	        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getRemoteAddr();  
	        }  
	        return ip;  
	    }  
} 
